#define _CRT_SECURE_NO_WARNINGS 2

#include"queue.h"

void QueueInit(Queue* q) {
	assert(q);
	q->head = NULL;
	q->tail = NULL;
	q->size = 0;
}

void QueuePush(Queue* q,datatype val) {
	assert(q);
	Node* newnode = (Node*)malloc(sizeof(Node));
	if (!newnode) {
		perror("newnode fail malloc");
		return;
	}
	newnode->val = val;
	newnode->next = NULL;
	if (!q->head) {
		assert(!q->tail);
		q->head = q->tail = newnode;
		q->tail->next = NULL;
	}
	else {
		q->tail->next = newnode;
		//newnode->next = NULL;
		q->tail = q->tail->next;
		//q->tail->next = NULL;
	}
	++q->size;
}

void QueuePop(Queue* q) {
	assert(q);
	assert(!QueueEmpty(q));
	if (q->head == q->tail) {
		free(q->head);
		q->head = q->tail = NULL;
	}
	else {
		Node* pos = q->head;
		q->head = q->head->next;
		free(pos);
		pos = NULL;
	}
	q->size--;
}

bool QueueEmpty(Queue* q) {
	return q->head == NULL&&q->tail==NULL;
	//return q->size==0;
}

datatype QueueFront(Queue* q) {
	assert(q);
	assert(!QueueEmpty(q));
	return q->head->val;
}

datatype QueueBack(Queue* q) {
	assert(q);
	assert(!QueueEmpty(q));
	return q->tail->val;
}

int QueueSize(Queue* q) {
	assert(q);
	return q->size;
}

void QueueDestroy(Queue* q) {
	assert(q);
	while (q->head) {
		Node* next = q->head->next;
		free(q->head);
		q->head = next;
	}
	q->head = q->tail = NULL;
	q->size = 0;
}

void QueuePrint(Queue* q) {
	assert(q);
	assert(!QueueEmpty(q));
	Node* cur = q->head;
	while (cur) {
		printf("%d ", cur->val);
		cur = cur->next;
	}
	putchar('\n');
}